﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Results;

namespace EffiProz.Core
{
    public class StatementHandler : Statement
    {
        public const int NONE = 0;
        public const int SQL_EXCEPTION = 1;
        public const int SQL_WARNING = 2;
        public const int SQL_NOT_FOUND = 3;
        public const int SQL_STATE = 4;

        //
        public const int CONTINUE = 5;
        public const int EXIT = 6;
        public const int UNDO = 7;

        //
        public int handlerType;

        //
        OrderedIntHashSet conditionGroups = new OrderedIntHashSet();
        HashSet conditionStates = new HashSet();
        public Statement statement;

        //
        public static StatementHandler[] emptyExceptionHandlerArray =
            new StatementHandler[] { };

        public StatementHandler(int handlerType)
            : base(StatementTypes.HANDLER, StatementTypes.X_SQL_CONTROL)
        {

            this.handlerType = handlerType;
        }

        public void addConditionState(String sqlState)
        {

            bool result = conditionStates.add(sqlState);

            result &= conditionGroups.isEmpty();

            if (!result)
            {
                throw Error.error(ErrorCode.X_42604);
            }
        }

        public void addConditionType(int conditionType)
        {

            bool result = conditionGroups.add(conditionType);

            result &= conditionStates.isEmpty();

            if (!result)
            {
                throw Error.error(ErrorCode.X_42604);
            }
        }

        public void addStatement(Statement s)
        {
            statement = s;
        }

        public bool handlesConditionType(int type)
        {
            return conditionGroups.contains(type);
        }

        public bool handlesCondition(String sqlState)
        {

            if (conditionStates.contains(sqlState))
            {
                return true;
            }

            String conditionClass = sqlState.Substring(0, 2);

            if (conditionStates.contains(conditionClass))
            {
                return true;
            }

            if (conditionClass.Equals("01"))
            {
                return conditionGroups.contains(SQL_WARNING);
            }

            if (conditionClass.Equals("02"))
            {
                return conditionGroups.contains(SQL_NOT_FOUND);
            }

            return conditionGroups.contains(SQL_EXCEPTION);
        }

        public int[] getConditionTypes()
        {
            return conditionGroups.toArray();
        }

        public String[] getConditionStates()
        {
            return (String[])conditionStates.toArray(
                new String[conditionStates.size()]);
        }

        public override Result execute(Session session)
        {

            if (statement != null)
            {
                return statement.execute(session);
            }
            else
            {
                return Result.updateZeroResult;
            }
        }

        public override String describe(Session session)
        {
            return "";
        }

        public override OrderedHashSet getReferences()
        {

            if (statement == null)
            {
                return new OrderedHashSet();
            }

            return statement.getReferences();
        }

        public override String getSQL()
        {

            StringBuilder sb = new StringBuilder(64);
            String s;

            s = handlerType == CONTINUE ? Tokens.T_CONTINUE
                                        : handlerType == EXIT ? Tokens.T_EXIT
                                                              : Tokens.T_UNDO;

            sb.Append(Tokens.T_DECLARE).Append(' ').Append(s).Append(' ');
            sb.Append(Tokens.T_HANDLER).Append(' ').Append(Tokens.T_FOR);
            sb.Append(' ');

            for (int i = 0; i < conditionStates.size(); i++)
            {
                if (i > 0)
                {
                    sb.Append(',');
                }

                sb.Append(Tokens.T_SQLSTATE).Append(' ');
                sb.Append('\'').Append(conditionStates.get(i)).Append('\'');
            }

            for (int i = 0; i < conditionGroups.size(); i++)
            {
                if (i > 0)
                {
                    sb.Append(',');
                }

                switch (conditionGroups.get(i))
                {

                    case SQL_EXCEPTION:
                        sb.Append(Tokens.T_SQLEXCEPTION);
                        break;

                    case SQL_WARNING:
                        sb.Append(Tokens.T_SQLWARNING);
                        break;

                    case SQL_NOT_FOUND:
                        sb.Append(Tokens.T_NOT).Append(' ').Append(Tokens.FOUND);
                        break;
                }
            }

            if (statement != null)
            {
                sb.Append(' ').Append(statement.getSQL());
            }

            return sb.ToString();
        }
    }
}
